<?php

namespace Api\Model;

use Think\Model;

class ShopsModel extends Model {

    /**
     *  获取店铺信息
     * @param type $shop_id
     * @return type
     */
    function getShopInfo($shop_id) {
        $info = $this->field('b.name as business_name,b.id as business_id,b.status as business_status,s.*')->alias('s')->where(array('s.id' => $shop_id))->join('LEFT JOIN __BUSINESS__ as b ON s.business_id=b.id')->find();
        return $info;
    }

    function getShopName($shop_id) {

        $cache_key = 'shop_name_key_' . $shop_id;

        $name = S($cache_key);

        if (!$name) {
            $shop_info = $this->getShopInfo($shop_id);

            if (!is_array($shop_info))
                return '';
            $name = "{$shop_info['business_name']}({$shop_info['name']})";
            S($cache_key, $name, 300);
        }
        return (string) $name;
    }

    /**
     * 获取正常的店铺信息
     * @param type $shop_id
     * @return boolean
     */
    function getNormalShopInfo($shop_id) {
        $info = $this->getShopInfo($shop_id);
        //验证已下架的 店铺和商家
        if (!is_array($info) || $info['business_status'] != 1 || $info['status'] != 1 || $info['show_type'] != 1)
            return false;
        return $info;
    }

    /**
     *   获取是否赞过店铺
     * @param type $user_id
     * @param type $shop_id
     * @return boolean
     */
    function isGivingShop($user_id, $shop_id) {

        $where = array(
            'user_id' => $user_id,
            'shop_id' => $shop_id
        );
        $count = M('UserGivingShop')->where($where)->count();
        if (is_numeric($count) && $count > 0)
            return true;
        return false;
    }

    /**
     *  新增赞店铺
     * @param type $user_id
     * @param type $shop_id
     * @return boolean
     */
    function addGivingShop($user_id, $shop_id) {
        $is_giving = $this->isGivingShop($user_id, $shop_id);

        if ($is_giving) {
            return false;
        }
        //验证店铺是否存在
        $count = $this->where(array('id' => $shop_id))->count();
   
        if ($count == 0)
            return false;

        $data = array(
            'user_id' => $user_id,
            'shop_id' => $shop_id,
            'create_time' => time(),
        );
        $result = M('UserGivingShop')->add($data);

        if ($result)
            $result = M('Shops')->where("id=$shop_id")->setinc('up_count');

        return $result;
    }

    /**
     *   取消对店铺的赞
     * @param type $user_id
     * @param type $shop_id
     * @return boolean
     */
    function delGivingShop($user_id, $shop_id) {
        $where = array(
            'user_id' => $user_id,
            'shop_id' => $shop_id,
        );
        $where = array('user_id' => $user_id, 'shop_id' => $shop_id,);
        $result = M('UserGivingShop')->where($where)->delete();
        if ($result)
            $result = M('Shops')->where("id=$shop_id")->setDec('up_count');
        return $result;
    }

    /**
     * @name 获取喜欢的商家选项
     */
    public function getFavoriteBusinessOptions($userid) {

        $where = '';
        return $this->field('id,name')->order('up_count DESC')->select();
        //用户喜欢的类型
        $userCategory = M('user_category as uc')->where("uc.user_id={$userid}")->field('uc.category_id as id,cl.category_id as fid')->join("cp_category_label as cl on uc.category_id=cl.id", 'LEFT')->select();
        print_r($userCategory);
        foreach ($userCategory as $key => $val) {
            switch ($val['fid']) {
                case 1:
            }
        }
        if ($userCategory) {
            $where .= "`category_id`={$userCategory}";
        }
    }

    /**
     *   推荐用户喜欢的列表
     * @param type $city_id
     * @param type $user_id
     */
    public function getRecomShopList($city_id, $user_id, $limit = array('1', '10'), $lon = '', $lat = '', $is_credit = false) {

        //用户特征
        $UserFeatures = D('User')->getUserFeatures($user_id);

        $where['s.city_id'] = $city_id;
        $where['c.id'] = array('gt', 0);
        $where['c.status'] = 1;
        $time = time();
        $where['_string'] = "c.show_type =1 OR (c.timing >0 AND c.timing < $time)";
        $where['b.status'] = 1;
        $where['s.status'] = 1;
        $where['s.show_type'] = 1;
        $order = 'view_num asc'; //默认 根据查看数排序 

        if ($is_credit) {
            $where['c.credit'] = array('GT', 0);
        } else {
            $where['c.credit'] = 0;
        }
        $qz = array(); //权重条件
        //分类的权重
        if (!emptys($UserFeatures['category'])) {
            $category_in = implode("','", $UserFeatures['category']);
            $qz[] = "(
			CASE
			WHEN s.category_id in ('$category_in') THEN
				0.01
			ELSE
				0
			END
		) ";
        }

        if (!emptys($UserFeatures['kouwei'])) {
            $taste_in = implode("','", $UserFeatures['kouwei']);
            $qz[] = "(
			CASE
			WHEN s.taste in ('$taste_in') THEN
				0.01
			ELSE
				0
			END
		) ";
        }
        $field = array('s.id as shop_id,s.name as shop_name, s.category_id,s.taste,s.image,s.business_start_time,s.business_end_time,tag,s.ave_price,s.up_count', 'c.start_time,c.expired_time,c.id as coupon_id,c.name as coupon_name,c.discount,c.credit,c.original_price,c.present_price,c.remark,c.coupon_count,c.for_count', 'b.name as business_name');
        if (count($qz) > 0) {
            $qz = implode('+', $qz);
            $field[] = "($qz)  as qz";
            $order = 'qz desc';
        }
        if (is_numeric($lat) && is_numeric($lon)) {
            $field[] = '(ACOS(SIN((' . $lat . ' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS((' . $lat . ' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS((' . $lon . '* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380) as juli';
            if (count($qz) > 0)
                $order = '(round(juli,1)-qz) asc'; //有权重
            else
                $order = 'juli asc'; //无权重
        }
        $coupon_sql = M('Coupon')->order('id desc')->select(false);
        $count = $this->alias('s')->field('count(distinct(s.id)) as count')->join("($coupon_sql) as c ON c.shops_id = s.id", 'LEFT')->join('__BUSINESS__ AS b ON b.id=s.business_id', 'LEFT')->where($where)->select();
        $count = (int) $count[0]['count'];
        $list = $this->alias('s')->field($field)->page($limit[0], $limit[1])->join("($coupon_sql) as c ON c.shops_id = s.id", 'LEFT')->join('__BUSINESS__ AS b ON b.id=s.business_id', 'LEFT')->where($where)->group('s.id')->order($order)->select();

        foreach ($list as $key => $info) {
            $category_name = getLabelNameById($info['category_id']);
            $taste_name = getLabelNameById($info['taste']);
            $label_list = array();
            if (!emptys($category_name))
                $label_list[] = array('id' => $info['category_id'], 'name' => $category_name);
            if (!emptys($taste_name))
                $label_list[] = array('id' => $info['taste'], 'name' => $taste_name);
            if (!emptys($info['tag']))
                $label_list = array_merge($label_list, explode(',', trim($info['tag'])));
            $list[$key]['label_list'] = $label_list;
        }

        return array('list' => $list, 'count' => $count, 'user_info' => (array) getArrayToKey(array($UserFeatures), 'category,kouwei')[0]);
    }

    /**
     *   获取城市热门列表
     * @param type $city_id
     * @param type $user_id
     */
    public function getCityHotShopList($city_id) {

        $where = '1=2 ';
        //用户喜欢的类型
        $userCategory = M('user_category as uc')->where("uc.user_id={$userid}")->field('uc.category_id as id,cl.category_id as fid')->join("cp_category_label as cl on uc.category_id=cl.id", 'LEFT')->select();
        if ($userCategory) {
            foreach ($userCategory as $key => $val) {
                switch ($val['fid']) {
                    case 1:
                        $where .= " OR  `category_id`={$val['id']}";
                        break;
                    case 2:
                        $where .= " OR  `taste`={$val['id']}";
                        break;
                }
            }
        }

        //用户的商区
        $userBusiness = M('user_business_district')->where("`user_id`={$userid}")->getField('business_district_id', true);
        if ($userBusiness) {
            $userBusiness = implode(',', $userBusiness);
            $where .= " OR  `business_id` IN ({$userBusiness})";
        }
        return $this->where($where)->field('id,name')->order('up_count DESC')->select();
    }

    public function getBusinessCouponList($city_id, $user_id, $limit, $longitude, $latitude, $is_credit = 0) {
        //用户特征
        $UserFeatures = D('User')->getUserFeatures($user_id);
        //查询条件
        $where['s.city_id'] = $city_id;
        $where['c.id'] = array('gt', 0);
        $where['c.status'] = 1;
        $time = time();
        $where['_string'] = "c.show_type =1 OR (c.timing >0 AND c.timing < $time)";
        $where['b.status'] = 1;
        $where['s.status'] = 1;
        $where['s.show_type'] = 1;
        if ($is_credit) {
            $where['c.credit'] = array('GT', 0);
        }
        $order = 'view_num asc'; //默认 根据查看数排序

        $qz = array(); //权重条件
        //分类的权重
        if (!emptys($UserFeatures['category'])) {
            $category_in = implode("','", $UserFeatures['category']);
            $qz[] = "(CASE WHEN s.category_id in ('$category_in') THEN 0.01 ELSE 0 END) ";
        }
        if (!emptys($UserFeatures['kouwei'])) {
            $taste_in = implode("','", $UserFeatures['kouwei']);
            $qz[] = "(CASE WHEN s.taste in ('$taste_in') THEN 0.01 ELSE 0 END) ";
        }

        $field = array('s.id as shop_id,s.name as shop_name, s.category_id,s.taste,s.image,s.business_start_time,s.business_end_time,s.coupon_count,s.for_count,tag,s.ave_price,s.up_count', 'c.start_time,c.expired_time,c.id as coupon_id,c.name as coupon_name,c.discount,c.credit,c.original_price,c.present_price,c.remark', 'b.name as business_name');
        if (count($qz) > 0) {
            $qz = implode('+', $qz);
            $field[] = "($qz)  as qz";
            $order = 'qz desc';
        }
        if (is_numeric($longitude) && is_numeric($latitude)) {
            $field[] = '(ACOS(SIN((' . $latitude . ' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS((' . $latitude . ' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS((' . $longitude . '* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380) as juli';
            if (count($qz) > 0)
                $order = '(round(juli,1)-qz) asc'; //有权重
            else
                $order = 'juli asc'; //无权重
        }

        $coupon_sql = M('Coupon')->order('id desc')->select(false);
        $count = $this->alias('s')->field('count(distinct(s.id)) as count')->join("($coupon_sql) as c ON c.shops_id = s.id", 'LEFT')->join('__BUSINESS__ AS b ON b.id=s.business_id', 'LEFT')->where($where)->select();
        $count = (int) $count[0]['count'];
        $list = $this->alias('s')->field($field)->page($limit[0], $limit[1])->join("($coupon_sql) as c ON c.shops_id = s.id", 'LEFT')->join('__BUSINESS__ AS b ON b.id=s.business_id', 'LEFT')->where($where)->group('s.id')->order($order)->select();

        foreach ($list as $key => $info) {
            $category_name = getLabelNameById($info['category_id']);
            $taste_name = getLabelNameById($info['taste']);
            $label_list = array();
            if (!emptys($category_name))
                $label_list[] = array('id' => $info['category_id'], 'name' => $category_name);
            if (!emptys($taste_name))
                $label_list[] = array('id' => $info['taste'], 'name' => $taste_name);
            if (!emptys($info['tag']))
                $label_list = array_merge($label_list, explode(',', trim($info['tag'])));
            $list[$key]['label_list'] = $label_list;
        }

        return array('list' => $list, 'count' => $count, 'user_info' => (array) getArrayToKey(array($UserFeatures), 'category,kouwei')[0]);
    }

    /**
     * @name 获取用户发布优惠券列表
     */
    public function getUserCouponList($city_id, $user_id, $limit, $longitude, $latitude, $is_credit = 0) {
        //用户特征
        $UserFeatures = D('User')->getUserFeatures($user_id);
        //查询条件
        $where['x.status'] = 3;

        $where['s.city_id'] = $city_id;
        $where['c.id'] = array('gt', 0);
        $where['c.status'] = 1;
        $time = time();
        $where['_string'] = "c.show_type =1 OR (c.timing >0 AND c.timing < $time)";
        $where['b.status'] = 1;
        $where['s.status'] = 1;
        $where['s.show_type'] = 1;
        if ($is_credit) {
            $where['c.credit'] = array('GT', 0);
        }

        $order = 'x.create_time DESC'; //默认 根据查看数排序

        $qz = array(); //权重条件
        //分类的权重
        if (!emptys($UserFeatures['category'])) {
            $category_in = implode("','", $UserFeatures['category']);
            $qz[] = "(CASE WHEN s.category_id in ('$category_in') THEN 0.01 ELSE 0 END) ";
        }
        if (!emptys($UserFeatures['kouwei'])) {
            $taste_in = implode("','", $UserFeatures['kouwei']);
            $qz[] = "(CASE WHEN s.taste in ('$taste_in') THEN 0.01 ELSE 0 END) ";
        }

        $field = array('s.id as shop_id,s.name as shop_name, s.category_id,s.taste,s.image,s.business_start_time,s.business_end_time,s.coupon_count,s.for_count,tag,s.ave_price,s.up_count', 'c.start_time,c.expired_time,c.id as coupon_id,c.name as coupon_name,c.discount,c.credit,c.original_price,c.present_price,c.remark,x.remark as pb_remark,x.coupon_code', 'b.name as business_name');
        if (count($qz) > 0) {
            $qz = implode('+', $qz);
            $field[] = "($qz)  as qz";
            $order = 'qz desc';
        }
        if (is_numeric($longitude) && is_numeric($latitude)) {
            $field[] = '(ACOS(SIN((' . $latitude . ' * 3.1415) / 180 ) *SIN((latitude * 3.1415) / 180 ) +COS((' . $latitude . ' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) *COS((' . $longitude . '* 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380) as juli';
            if (count($qz) > 0)
                $order = '(round(juli,1)-qz) asc'; //有权重
            else
                $order = 'juli asc'; //无权重
        }


        $list = M('coupon_list')->alias('x')
                ->page($limit[0], $limit[1])
                ->field($field)
                ->join("__SHOPS__ as s on x.shops_id=s.id", 'LEFT')
                ->join("__COUPON__ as c on x.coupon_id=c.id")
                ->join('__BUSINESS__ AS b ON b.id=s.business_id', 'LEFT')
                ->where($where)->order($order)
                ->select();
        $count = M('coupon_list')->alias('x')
                ->join("__SHOPS__ as s on x.shops_id=s.id", 'LEFT')
                ->join("__COUPON__ as c on x.coupon_id=c.id")
                ->join('__BUSINESS__ AS b ON b.id=s.business_id', 'LEFT')
                ->where($where)
                ->count();

        foreach ($list as $key => $info) {
            $category_name = getLabelNameById($info['category_id']);
            $taste_name = getLabelNameById($info['taste']);
            $label_list = array();
            if (!emptys($category_name))
                $label_list[] = array('id' => $info['category_id'], 'name' => $category_name);
            if (!emptys($taste_name))
                $label_list[] = array('id' => $info['taste'], 'name' => $taste_name);
            if (!emptys($info['tag']))
                $label_list = array_merge($label_list, explode(',', trim($info['tag'])));
            $list[$key]['label_list'] = $label_list;
            $list[$key]['need_credit'] = getReceiveCredit($list[$key]['discount']);
            $list[$key]['coupon_code'] = couponEDC($list[$key]['coupon_code'], true);
        }
        return array('list' => $list, 'count' => $count, 'user_info' => (array) getArrayToKey(array($UserFeatures), 'category,kouwei')[0]);
    }

}
